<?php 
namespace lib;
class PHP_Mac
{
    private $result = array();
    private $macAddrs = array(); // 所有mac地址
    private $macAddr;            // 第一个mac地址

    public function __construct($OS)
    {
        $this->getMac($OS);
    }

    public function getMacAddr()
    {
        return $this->macAddr;
    }

    public function getMacAddrs()
    {
        return $this->macAddrs;
    }

    private function getMac($OS)
    {
        switch (strtolower($OS)) {
            case "unix":
            case "solaris":
            case "aix":
                // To be implemented for Unix-based systems
                break;
            case "linux":
                $this->getLinux();
                break;
            default:
                $this->getWindows();
                break;
        }
    }

    private function getLinux()
    {
        @exec("/usr/sbin/ifconfig -a", $this->result);
        //var_dump($this->result);
        return $this->result;
    }

    private function getWindows()
    {
        @exec("ipconfig /all", $this->result);
        if (empty($this->result)) {
            $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";
            if (is_file($ipconfig)) {
                @exec($ipconfig." /all", $this->result);
            } else {
                $ipconfig = $_SERVER["WINDIR"]."\system\ipconfig.exe";
                if (is_file($ipconfig)) {
                    @exec($ipconfig." /all", $this->result);
                }
            }
        }
    }

    public function parseMacAddr()
    {
        $tem = array();
        foreach ($this->result as $val) {
            if (preg_match("/([0-9a-f][0-9a-f]:){5}[0-9a-f][0-9a-f]/i", $val, $tem)) {
                $this->macAddr = $tem[0]; // 多个网卡时，会返回第一个网卡的mac地址，一般够用。
                $this->macAddrs[] = $tem[0]; // 返回所有的mac地址
                break;
            }
        }
    }
}